package com.nuyoah.service.impl;

import com.nuyoah.common.dto.CourseDto;
import com.nuyoah.entity.Course;
import com.nuyoah.entity.User;
import com.nuyoah.mapper.CourseMapper;
import com.nuyoah.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuyoah.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 存储课程的详细信息 服务实现类
 * </p>
 *
 * @author xyx
 * @since 2024-06-15
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private UserService userService;

    @Override
    public List<Course> getCourseListByStudentId(Integer id) {
        return this.baseMapper.getCourseListByStudentId(id);
    }

    @Override
    public List<CourseDto> getCourseDtoList(List<Course> courseList) {
        List<CourseDto> courseDtoList = new ArrayList<>();
        for (Course course : courseList) {
            CourseDto courseDto = new CourseDto();
            // 复制课程基本信息
            BeanUtils.copyProperties(course, courseDto);
            User user = userService.getById(course.getTeacherId());
            if (user != null) {
                courseDto.setTeacherName(user.getRealName());
            } else {
                courseDto.setTeacherName("未知");
            }
            courseDtoList.add(courseDto);
        }
        return courseDtoList;
    }

    @Override
    public List<Course> getAllCourseList() {
        return this.baseMapper.getAllCourseList();
    }

    @Override
    public String addCourse(Course course) {
        this.save(course);
        return "添加成功";
    }

    @Override
    public String deleteCourse(Integer id) {
        //先判断课程是否存在
        Course course = this.getById(id);
        if (course == null) {
            return "课程不存在";
        }
        this.removeById(id);
        return "删除成功";
    }

    @Override
    public String updateCourse(Course course) {
        //先判断课程是否存在
        Course oldCourse = this.getById(course.getId());
        if (oldCourse == null) {
            return "课程不存在";
        }
        this.updateById(course);
        return "更新成功";
    }

}
